<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            选中退货
        </div>
    </header>
    <div class="aui-content aui-margin-b-15" style="margin-top:50px;">
        <ul class="aui-list aui-form-list">

            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">发货单号</div>
                    <input type="text" class="aui-input" placeholder="发货单号" style="width: 80%;font-size: 16px;"
                        id="consignment" disabled="true" />
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">送检单号</div>
                    <input type="text" class="aui-input" placeholder="送检单号" style="width: 80%;font-size: 16px;"
                        id="inspection" disabled="true" />
                </div>
            </li>
            <li class="aui-list-item">
                <div class="aui-list-item-inner">
                    <div class="aui-list-item-label">拒收原因</div>
                    <textarea id="remark" class="aui-input" placeholder="录入拒收原因" style="width: 80%;font-size: 16px;"></textarea>
                    <!-- <input type="text" class="aui-input" placeholder="录入拒收原因" style="width: 80%;font-size: 16px;"
                        id="remark" onclick="getIdSelector();" /> -->
                    <!-- <select id="remark">
                    </select> -->
                </div>
            </li>
            <div class="aui-content" style="background-color: #ffffff">
                <ul class="aui-list-view aui-grid-view" id="imgslist">
                    <li class="aui-list-view-cell aui-img aui-col-xs-4" id="addpic" onclick="imgClick()">
                        <img class="aui-img-object" src="../image/add.jpg">
                    </li>
                </ul>
            </div>

        </ul>

        <ul class="ui-selectee" id="tbodyHtml">

        </ul>

        <p></p>
        <p></p>
        <div style="height:60px;"></div>
        <footer class="aui-bar aui-bar-tab" id="footer">
            <div class="aui-btn aui-btn-info aui-btn-block" id="submitButton" onclick="save()">提交</div>

        </footer>

    </div>


</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/clickThrottle.js"></script>
<script type="text/javascript" src="../script/hammer.min.js"></script>
<script type="text/javascript">
    //光标所在id
    //光标所在id
    var idSelector = "";
    var scanRule = ""; //条码解析规则
    var uiMediaScanner = null;

    var arrSave = [];

    //初始化查询仓库下拉框
    apiready = function () {
        $("#boxnum").focus();
        idSelector = "boxnum";
        var consignment = api.pageParam.consignment;//发货单号
        var inspection = api.pageParam.inspection;//送检单号
        arrSave = api.pageParam.list;//选中箱数据
        setTable(arrSave);
        console.log(JSON.stringify(arrSave));
        $("#consignment").val(consignment);
        $("#inspection").val(inspection);

        // 引入多选模块
        uiMediaScanner = api.require('UIMediaScanner');
        // 引入过滤压缩模块
        imageFilter = api.require("imageFilter");
        // 引入图片浏览模块
        imageBrowser = api.require('imageBrowser');

        var query = api.pageParam.query;

        //查询条码解析规则
        initScanRule();

        //查询来料拒收原因
        // selectRemark();
    }
   //查询来料拒收原因下拉框
   function selectRemark() {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getUdiList";
        var data = {
            values: {
                code: "REFUSR_REASON",
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var map = eval("(" + data + ")");
                var list = eval(map.list);
                console.log(JSON.stringify(list))
                var html = "";
                for (var i = 0; i < list.length; i++) {
                    console.log(list[i].value)
                    html += "<option value='" + list[i].value + "'>" + list[i].label + "</option>";
                }
                $api.html($api.byId("remark"), html);

            }
        });
    }

    // 获取光标所在组件的id
    function getIdSelector() {
        var e = event || window.event;
        var el = e.srcElement || e.target;
        idSelector = el.id;
        $("#" + el.id).select();
    }

    //查询扫描规则
    function initScanRule() {
        var serverUrl = localStorage.getItem('serverUrl');
        var un = localStorage.getItem("un");
        var url = serverUrl + "/app/getTmScanRule";
        var data = {
            values: {
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    scanRule = myobj.scanRule
                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            }
        });
    }

    //扫描
    function doScan() {
        var moduleScanner = api.require('moduleScanner');
        var params = {
            top: 150, //扫描窗口的上边距
            width: 250, //扫描窗口的宽
            height: 250, //扫描窗口的高
            useColor: false, //是否使用自己设定的颜色(startColor和endColor),
            //如果不使用设定的颜色就使用默认的那张网格图
            startColor: '#0F08C8FF', //渐变起始颜色
            endColor: '#7F08C8FF', //渐变结束颜色
            animTime: 2200, //扫描动画时间,单位为毫秒
        };
        moduleScanner.toScannerActivityForResult(params, function (ret, err) {
            //1：调出库位
            if (idSelector == 'workCellCode') {

                $("#workCellCode").val(ret);
                //查询调出库位
                getWorkCell(ret, idSelector, "1");

                //24：调入库位
            } else if (idSelector == 'relWorkCellCode') {

                $("#relWorkCellCode").val(ret);
                //查询调入库位
                getWorkCell(ret, idSelector, "2");

                //5：扫描条码
            } else if (idSelector == 'boxnum') {
                // $("#boxnum").blur();
                $("#boxnum").attr('disabled', true);
                tmSplit(ret);
            }
        });
    }



    //保存按钮
    function save() {

         if (!clickThrottle()) {
            return;
        }

        // 发货单号
        var consignment = $("#consignment").val();
        // 送检单号
        var inspection = $("#inspection").val();
        //获取imgslist中所有的img，保存图片和异常业务记录的关系
        var imgs = document.getElementsByTagName('img');
        var names = [];

        for (var i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            var srcStr = img.getAttribute('src');
            var arrs = srcStr.split('\/');
            var nameStr = arrs[arrs.length - 1];
            //alert(nameStr);
            if ("add.jpg" != nameStr) {
                names[i] = nameStr;
            }
        }
        var picNames = JSON.parse(JSON.stringify(names));
        //原因
        var remark = $("#remark").val();

        const submitButton = document.getElementById('submitButton');
        submitButton.style.pointerEvents = "none"; // 禁用提交按钮

        api.showProgress({
            title: '保存中...',
        });

        

        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/inspectionRejectGoods";
        var data = {
            values: { ////以表单方式提交参数（JSON对象）
                list: JSON.stringify(arrSave),
                un: un,
                remark: remark,
                picNames: picNames,
                consignment: consignment,
                inspection: inspection
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == '0') {
                    submitButton.style.pointerEvents = "auto"; // 启用提交按钮
                    api.hideProgress();
                    api.toast({
                        msg: "退货成功",
                        duration: 3000
                    }); //清空表单

                    var map = myobj.data;
                    $("#boxnum").attr('disabled', false);
                    $("#boxnum").focus();
                    idSelector = "boxnum";
                    //清空表格数据
                    $api.html($api.byId("tbodyHtml"), "");
                    //删除成功的箱
                    arrSave = [];
                    api.closeWin();
                    api.execScript({
                        name: "uwmInspectionRejectBox",
                        script: 'doSearch()'
                    });
                    // api.execScript({
                    //     name: 'uwmSHVerification_djg',
                    //     script: 'searchDetails("' + consignment + "" + '")'
                    // });
                } else if (myobj.code == '1') {
                    submitButton.style.pointerEvents = "auto"; // 启用提交按钮
                    console.log(123456)
                    $("#boxnum").attr('disabled', false);
                    $("#boxnum").val("");
                    $("#boxnum").select();
                    idSelector = "boxnum";
                    // removeAll(myobj.list);
                    api.hideProgress();
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                submitButton.style.pointerEvents = "auto"; // 启用提交按钮
                $("#boxnum").attr('disabled', false);
                $("#boxnum").val("");
                $("#boxnum").select();
                idSelector = "boxnum";
                api.hideProgress();
                $("#message").val("");
                alert(JSON.stringify(err));
            }
        });
    }



    //自动保存
    function saveAuto(sm, mrlCode, lotCode, qty, boxnum, tmID) {
        //判断箱号是否重复
        for (var i = 0; i < arrSave.length; i++) {
            if (boxnum == arrSave[i].boxnum) {
                api.toast({
                    msg: '箱号已存在！',
                    duration: 3000
                });
                return;
            }
        }
        message = "提示信息：" + boxnum + "   扫描成功"
        $("#message").val(message);
        message = "";
        var model = {
            mrlCode: mrlCode, //物料号
            lotCode: lotCode, //批次号
            qty: qty, //转移数量
            tm: sm, //箱号
            boxnum: boxnum, //条码
            tmID: tmID //条码ID
        }
        arrSave.push(model);
        setTable(arrSave);
    }

    function setTable(list) {
        var html = "";
        for (var i = 0; i < list.length; i++) {
            html += "<li class='sortable ui-selectee ui-sortable'>";
            html += "<ul class='aui-list aui-media-list ui-selectee'>";
            html += "<li class='aui-list-item  ui-selectee'>";
            html += "<div class='aui-media-list-item-inner ui-selectee'>";
            html += "<div class='aui-list-item-inner ui-selectee'>";
            html += "<div class='aui-list-item-text ui-selectee' style='height: 15px;'>";
            html += "<div class='aui-list-item-label ui-selectee list-tr-title'>箱号</div>";
            html += "<div class='aui-list-item-inner ui-selectee'>" + list[i].boxnum + "</div>";
            html += "</div>";
            html += "<div class='aui-list-item-text ui-selectee' style='height: 15px;'>";
            html += "<div class='aui-list-item-label ui-selectee list-tr-title'>数量</div>";
            html += "<div class='aui-list-item-inner ui-selectee'>" + list[i].qty + "</div>";
            html += "</div>";
            html += "<div class='aui-list-item-text ui-selectee' style='height: 15px;'>";
            html += "<div class='aui-list-item-label ui-selectee list-tr-title'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</div>";
            html += "<div class='aui-list-item-inner ui-selectee'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</div>";
            html += "<div class='aui-list-item-right aui-btn ui-selectee' style='background:red;color:#f5f5f5;' onclick='remove(\"" + list[i].boxnum + "\");'>移除</div>";
            html += "</div>";
            html += "</div>";
            html += "</li>";
            html += "</ul>";
            html += "</li>";
        }
        // $api.html($api.byId("tbodyHtml"), html);
    };
    
    function remove(boxnum) {
        for (var i = 0; i < arrSave.length; i++) {
            if (arrSave[i].boxnum == boxnum) {
                arrSave.splice(i, 1)
                setTable(arrSave);
            }

        }

    };

    function removeAll(list) {
        setTable(list);
        arrSave = list;
    };

    //扫描之后条码解析
    function tmSplit(sm) {
        // $("#tm").val(sm);
        //直接解析
        if (scanRule == "old") {

            //本地解析
            localAnalyze(sm);

        } else {

            //后台解析
            postAnalyze(sm);
        }
    }

    //本地解析
    function localAnalyze(sm) {
        var arr = sm.split(",");
        var mrlCode = "";
        if (arr[1] == null || arr[1] == undefined) {
            $("#mrlCode").val("");
        } else {
            mrlCode = arr[1];
        }
        var qty = "";
        if (arr[2] == null || arr[2] == undefined) {
            $("#qty").val("");
        } else {
            qty = arr[2];
        }
        var lotCode = "";
        if (arr[3] == null || arr[3] == undefined) {
            $("#lotCode").val("");
        } else {
            lotCode = arr[3];
        }
        var tmID = "";
        if (arr[4] == null || arr[4] == undefined) {
            $("#tmID").val("");
        } else {
            tmID = arr[4];
        }
        var boxnum = "";
        if (arr[9] == null || arr[9] == undefined) {
            $("#boxnum").val("");
        } else {
            boxnum = arr[9];
        }
        boxnumCheck(sm, mrlCode, lotCode, qty, boxnum, tmID);
        //自动入库
        // saveAuto(sm, mrlCode, lotCode, qty, boxnum, tmID);
    }

    //后台解析条码
    function postAnalyze(sm) {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/analysisBarCodeCommon";
        var data = {
            values: {
                tm: sm, //条码
                un: un
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == '0') {

                    var map = myobj.data;
                    for (var key in map) {
                        $("#" + key).val(map[key]);
                    }
                    $("#boxnum").val("");
                    //物料号
                    var mrlCode = map["mrlCode"];
                    //批次号
                    var lotCode = map["lotCode"];
                    //转移数量数量
                    var qty = map["qty"];
                    //条码
                    var tm = map["tm"];
                    //箱号
                    var boxnum = map["boxnum"];
                    //tmID
                    var tmID = map["tmID"];
                    console.log("2222");
                    boxnumCheck(tm, mrlCode, lotCode, qty, boxnum, tmID);

                } else if (myobj.code == '1') {
                    $("#boxnum").attr('disabled', false);
                    $("#boxnum").val("");
                    $("#boxnum").select();
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }


    //箱号监听回车事件
    $("#boxnum").on('keypress', function (e) { //#keyword为input文本框
        if (!clickThrottle()) {
            $("#boxnum").val("");
            return;
        }
        var keycode = e.keyCode;
        var tm = $(this).val();
        $("#boxnum").val("");
        if (keycode == '13') {
            if (tm != null && tm != "" && tm != undefined) {
                // $("#boxnum").blur();
                // $("#boxnum").attr('disabled', true);
                console.log(tm);
                // $("#boxnum").select();
                //调用条码解析+保存事件
                tmSplit(tm);
            }
        }
    });

    function boxnumCheck(tm, mrlCode, lotCode, qty, boxnum, tmID) {
        var consignment = $("#consignment").val();
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/boxnumAndConsignmentCheck";
        var data = {
            values: { ////以表单方式提交参数（JSON对象）
                boxnum: boxnum,
                un: un,
                consignment: consignment,
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == '0') {

                    //自动保存
                    saveAuto(tm, mrlCode, lotCode, qty, boxnum, tmID);
                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                    return;
                }
            } else {
                return;
            }
        });
    }

    //返回按钮
    function closeWin() {
        api.closeWin({});
        api.execScript({
            name: "uwmInspectionRejectBox",
            script: 'doSearch()'
        });
    }






    function imgClick() {
        // 获取图片宽高
        var normalW = $("#addpic img").width();

        api.actionSheet({
            title: '选择图片来源',
            buttons: ['照相机', '浏览相册']
        }, function (ret, err) {
            var index = ret.buttonIndex;
            switch (index) {
                // 拍照
                case 1:
                    // 打开拍照
                    api.getPicture({
                        sourceType: "camera",
                        encodingType: "jpg",
                        destinationType: "url",
                        mediaValue: "pic",
                        quality: 50,
                        saveToPhotoAlbum: true
                    }, function (ret, err) {
                        if (ret && ret.data) {
                            // 拍照返回的本地路径
                            var returnUrl = ret.data;
                            // 图片压缩
                            imgCompress(returnUrl, 0.5, 0.5, getExt(returnUrl), function (compressImg) {
                                var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4' onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                    "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                // 追加图片
                                $("#addpic").before(showImgHtml);
                                // ########################################  绑定长按事件 ########################
                                addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                //上传图片
                                uploadFile(compressImg);
                            });
                        } else {
                            api.toast({
                                msg: '没有选择，或者选择出错'
                            });
                        }
                    });
                    break;
                // 打开图片选择器
                case 2:
                    uiMediaScanner.open({
                        type: 'picture',
                        column: 4,
                        classify: true,
                        max: 5,
                        sort: {
                            key: 'time',
                            order: 'desc'
                        },
                        texts: {
                            stateText: '已选*项',
                            cancelText: '取消',
                            finishText: '完成'
                        },
                        styles: {
                            bg: '#fff',
                            mark: {
                                icon: '',
                                position: 'bottom_left',
                                size: 20
                            },
                            nav: {
                                bg: '#b23e4b',
                                stateColor: '#fff',
                                stateSize: 18,
                                cancelBg: 'rgba(0,0,0,0)',
                                cancelColor: '#fff',
                                cancelSize: 18,
                                finishBg: 'rgba(0,0,0,0)',
                                finishColor: '#fff',
                                finishSize: 18
                            }
                        }
                    }, function (ret) {
                        if (ret) {
                            for (var i = 0; i < ret.list.length; i++) {
                                var selectImg = ret.list[i];
                                // 获取图片的路径
                                var selectimgPath = selectImg.path;
                                var selectimgThumbPath = selectImg.thumbPath;
                                // 图片压缩
                                imgCompress(selectimgPath, 0.5, 0.5, selectImg.suffix, function (compressImg) {
                                    var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4' onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                        "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                    // 追加图片
                                    $("#addpic").before(showImgHtml);
                                    // ########################################  绑定长按事件 ########################
                                    addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                    // ################### 上传图片 #########################
                                    uploadFile(compressImg);
                                });
                            }
                        }
                    });
                    break;
            }
        });
    }

    // 为图片添加点击预览功能,排除添加按钮
    function lookImg(compressImg) {
        // 定义一个数组，存储需要预览的图片
        var browerImgs = [];
        // 调用图片预览函数
        browerImgs.push(compressImg);
        openImageBrowser(browerImgs);
    }

    // 图片压缩
    // imgsrc：源图片的路径
    // quality：图片压缩质量，一般建议0.5
    // scale：图片压缩比例，也是建议0.5
    // ext：源图片拓展名
    // callback：转换成功之后回调函数
    function imgCompress(imgsrc, quality, scale, ext, callback) {
        // 压缩文件的保存目录
        var savePath = api.cacheDir + "/" + getNowFormatDate() + "/";
        // 压缩文件生成的随机文件名称
        var savename = NewGuid() + "." + ext;
        imageFilter.compress({
            img: imgsrc,
            quality: quality,
            scale: quality,
            save: {
                album: false,
                imgPath: savePath,
                imgName: savename
            }
        }, function (ret, err) {
            if (ret) {
                callback(savePath + savename);
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    // 打开图片浏览
    // imgs：需要预览的图片集合
    function openImageBrowser(imgs) {
        imageBrowser.openImages({
            imageUrls: imgs,
            showList: false,
            activeIndex: 0
        });
    }

    // 添加长按方法
    function addPress(obj, index) {
        // 获取目前长按的对象
        var hammertime = new Hammer(obj[0]);
        // 绑定长按对象
        hammertime.on("press", function (e) {
            api.confirm({
                title: '温馨提示',
                msg: '您确定要删除该图片吗？',
                buttons: ['确定', '取消']
            }, function (ret, err) {
                if (ret.buttonIndex == 1) {
                    // 移除自己
                    $(obj).remove();
                    api.toast({
                        msg: '删除成功！'
                    });
                }
            });
        });
    }

    // 上传图片
    // url：上传的url地址
    // data：上传的文件
    // callback：上传成功返回地址
    function uploadFile(data) {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/uploadPhotosAPP";
        var data = {
            values: {
                un: un
            },
            files: {
                file: data
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == "0") {
                    console.log("上传成功");
                } else if (myobj.code == "1") {
                    alert("上传失败");
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    // 获取当前的时间，拼接成2015-11-09这样的格式，主要用于对图片进行时间分类
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate
        return currentdate;
    }

    // 获取文件拓展名
    function getExt(fileName) {
        return fileName.substring(fileName.lastIndexOf('.') + 1);
    }

    // 生成guid,主要用于生成随机文件名
    function NewGuid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }

        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }
</script>

</html>